import { Hole } from '@/types';
import {
  ProColumns,
  ProForm,
  ProFormDependency,
} from '@ant-design/pro-components';
import { Space, Typography } from 'antd';
import { get, uniqueId, values } from 'lodash-es';
import { useEffect, useRef } from 'react';
import { CustomEditableTable } from '../CustomEditableTable';
import { faceOptions } from '../constants';
import { Axis } from '../types';
import { isLockAxis } from '../utils/axis';
import { AxisBackup } from '../AxisBackup';
import {
  FormCount,
  FormFace,
  FormPoint,
  FormSize,
  FormTitle,
  createDepthRule,
  gtZeroRule,
  useDepthLimit,
} from '../CustomForm';
import { DataAdd } from '../DataAdd';

interface Props {
  holeId?: string;
  onSelectHole: (holeId: string) => void;
}

export const HoleEditor = (props: Props) => {
  const refs = useRef<Record<string, HTMLDivElement | null>>({});
  useEffect(() => {
    if (!props.holeId) return;
    refs.current[props.holeId]?.scrollIntoView();
  }, [props.holeId]);

  const path = ['plank', 'holes'];
  const columns: ProColumns[] = [
    {
      title: '序号',
      valueType: 'index',
      editable: false,
    },
    {
      title: '基准面',
      dataIndex: 'plankFaceId',
      valueType: 'select',
      fieldProps: {
        options: faceOptions,
      },
      editable: false,
    },
    {
      title: '孔直径',
      dataIndex: 'diameter',
      valueType: 'digit',
      formItemProps: () => {
        return {
          rules: [gtZeroRule],
        };
      },
    },
    {
      title: '孔深',
      dataIndex: 'depth',
      valueType: 'digit',
      formItemProps: (form, config) => {
        const { plankFaceId } = config.entity;
        const size = form.getFieldValue(['plank', 'size']);
        return {
          rules: [gtZeroRule, createDepthRule({ size, plankFaceId })],
        };
      },
    },
    ...values(Axis).map<ProColumns>((axis) => ({
      editable(_, { plankFaceId }) {
        return !isLockAxis({ axis: Axis[axis], plankFaceId });
      },
      title: (
        <span>
          圆心 <AxisBackup axis={axis} />
        </span>
      ),

      dataIndex: ['start', axis],
      valueType: 'digit',
    })),
    {
      title: '操作',
      valueType: 'option',
    },
  ];

  return (
    <>
      <CustomEditableTable
        title={
          <FormTitle
            title="孔列表"
            extra={<FormCount name={['plank', 'holes']} />}
          />
        }
        name={path}
        columns={columns}
        rowKey={'holeId'}
        editableRowId={props.holeId}
        onEditable={(id) => {
          console.log('onEditable');
          props.onSelectHole(id);
        }}
        dataAddRender={({ addRow }) => <HoleAdd onConfirm={addRow} />}
      />
    </>
  );
};

export type HoleAddData = Pick<
  Hole,
  'holeId' | 'plankFaceId' | 'start' | 'diameter' | 'depth'
>;

function HoleAdd(props: { onConfirm: (data: HoleAddData) => void }) {
  const path = ['temp', 'hole'];

  function onConfirm(data: Omit<HoleAddData, 'holeId'>) {
    props.onConfirm({
      holeId: uniqueId('temp-hole-id-'),
      ...data,
    });
  }

  const limitValue = useDepthLimit(path);

  return (
    <>
      <FormTitle title="孔添加" />
      <DataAdd baseName={path} onConfirm={onConfirm}>
        {({ addBaseName }) => {
          return (
            <>
              <FormFace label="基准面" name={addBaseName(['plankFaceId'])} />
              <ProForm.Item label="孔起点(圆心)">
                <FormPoint name={addBaseName(['start'])} />
              </ProForm.Item>
              <ProForm.Item label="孔尺寸">
                <Space>
                  <FormSize name={addBaseName(['diameter'])} desc="直径" />
                  <FormSize name={addBaseName(['depth'])} desc="孔深" />
                </Space>
              </ProForm.Item>
            </>
          );
        }}
      </DataAdd>
    </>
  );
}
